<template>
  <el-row style="height: 100vh; display: flex" :gutter="20">
    <el-col :span="5" id="left-tree" class="left-tree">
      <div class="comp-tree"
        style="height: 100%;  padding: 10px;     width: 17.3vw; border-right: 1px solid #dfe6ec; display: block; overflow: auto">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
        <el-tree class="filter-tree" default-expand-all :filter-node-method="filterNode" ref="SlotTree"
          :default-expanded-keys="treeData" :current-node-key="currentNodekey" :data="treeList" :props="defaultProps"
          :expand-on-click-node="false" highlight-current :node-key="NODE_KEY" @node-click="handleNodeClick">
          <template v-slot="{ node, data }">
            <el-tooltip :content="data.label" placement="top">
              <span>{{ data.label }}</span>
            </el-tooltip>
          </template>
        </el-tree>
        <!-- <div id="resize" class="resize" title="收缩侧边栏">
          <p>⋮</p>
        </div> -->
      </div>
      <!-- </div>
    </div> -->
    </el-col>
    <!-- <el-col :span="6">
      <div class="app-container calendar-list-container">
        <div id="treeBox" class="filter-container">
          <el-table :data="treeList" style="width: 100%;" row-key="id" border lazy :load="load"
            @row-click="getListByTreeId">
            <el-table-column prop="name" label="名称" sortable />
          </el-table>
        </div>
      </div>
    </el-col> -->
    <el-col id="right-content" class="right-content" :offset="0" :span="17">
      <div class="app-container">
        <div class="filter-container">
          <!-- <div class="filter-item">
            <span class="span">字段名称:</span>
            <el-input v-model="listQuery.columnName" placeholder="请输入字段名称" style="width: 200px" />
          </div>
          <div class="filter-item">
            <span class="span">字段注解:</span>
            <el-input v-model="listQuery.columnComment" placeholder="请输入字段注解" style="width: 200px" />
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button> -->

          <!--          <el-button v-waves v-permission="['metadata:column:add']" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">-->
          <!--            {{ $t('table.add') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:delete']" class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBathDelete">-->
          <!--            {{ $t('table.delete') }}-->
          <!--          </el-button>-->
          <!--          <el-button v-waves v-permission="['metadata:column:import']" class="filter-item" type="primary" icon="el-icon-upload2" @click="handleImport">-->
          <!--            {{ $t('table.import') }}-->
          <!--          </el-button>-->
          <!-- <el-button v-waves v-permission="['metadata:column:export']" :loading="downloadLoading" class="filter-item"
            type="primary" icon="el-icon-download" @click="handleExport">
            {{ $t('table.export') }}
          </el-button> -->
        </div>
        <div class="filter-container">
          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
            @click="handleCreate">
            {{ $t('table.entity') }}
          </el-button> -->

          <!-- <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search"
            @click="handleCheck">
            {{ $t('table.checkentity') }}
          </el-button> -->
        </div>
        <div class="right">
          <div class="top">
            <el-table ref="table" :key="tableKey" v-loading="listLoading" element-loading-text="正在加载，请稍后" :data="list"
              border fit highlight-current-row @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column align="center" type="index" width="50" label="序号">
                <template slot-scope="scope">
                  <span>{{ (listQuery.page - 1) * listQuery.limit + scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column align="center" label="拖拽" width="80">
            <template slot-scope="{}">
              <svg-icon class="drag-handler" icon-class="drag" />
            </template>
          </el-table-column> -->
              <el-table-column v-for="(value, key) in obj" :prop="key" :key="key" align="center" :label="key"
                min-width="150px">
              </el-table-column>
            </el-table>
          </div>
          <div class="buttom">

            <div style="float: right;display: flex;align-items: center;justify-content: center;">


              <el-select size="10px" v-model="listQuery.limit" @change="getList()" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>


              <i style="width: 40px; " class="el-icon-arrow-left" @click="left"></i>
              <i style="width: 40px;" class="el-icon-arrow-right" @click="right"></i>
              <span>
                前往
                <input style="width: 40px; text-align: center;" :disabled="isboolinput"
                  v-model="listQuery.page"></input>
                页
              </span>
            </div>
          </div>
        </div>




        <!-- <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" /> -->
      </div>
    </el-col>
  </el-row>
</template>

<style>
/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999;
  /* 确保工具提示显示在顶部 */
}
</style>

<script>
import { fetchsourceList, getTotalModel } from '@/api/metadata/source'
import { deletecolumn, fetchcolumnList, exportcolumn, updatecolumn } from '@/api/metadata/column'

import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import Pagination from '@/components/Pagination'
import Sortable from 'sortablejs'
import { fetchMetadataLabelGroupList } from '@/api/metadata/label/metadataLabelGroup'

export default {
  name: 'columnList',
  components: { Pagination },
  directives: { waves, permission },
  data() {
    return {
      isboolinput: true,
      treeList: [],
      options: [{
        value: '15',
        label: '15'
      }, {
        value: '20',
        label: '20'
      }, {
        value: '25',
        label: '25'
      }, {
        value: '30',
        label: '30'
      }, {
        value: '35',
        label: '35'
      }],
      filterText: '',
      tableKey: 0,
      labelList: [],
      list: null,
      obj: {},
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: 10,
      listQuery: {
        columnName: undefined,
        ancestralId: '3',
        page: 1,
        limit: 15,
      },
      entityQuery: {},
      currentNodekey: '',
      treeData: [],
      input: "",
      updateWindowHeight: "",
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      NODE_KEY: 'id',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getTreeList()
    window.addEventListener('resize', this.sizeFun)
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  mounted() {
    this.sizeFun();
  },
  methods: {
    sizeFun() {
      this.size = document.documentElement.clientHeight - 350

    },
    left() {
      if (this.listQuery.page == 1) {
        this.listQuery.page = 1
        this.$message({
          type: 'error', // success error warning
          message: '这已经是第一页了',
          duration: 2000,
        })
      } else {
        this.listQuery.page = Number(this.listQuery.page) - 1
      }
      this.getList()
    },
    right() {

      if (this.list.length < this.listQuery.limit) {
        this.$message.error("已经是最后一页了")

      } else {
        this.listQuery.page = Number(this.listQuery.page) + 1

      }
      this.getList()

    },
    dragControllerDiv() {
      let left = document.getElementById('left-tree')
      let line = document.getElementById('resize')
      let right = document.getElementById('right-content')
      // 鼠标按下事件
      line.onmousedown = function (e) {
        let startX = e.clientX
        line.left = line.offsetLeft
        // 鼠标拖动事件
        document.onmousemove = function (e) {
          let moveLen = line.left + (e.clientX - startX)
          if (moveLen >= document.body.clientWidth * 0.1 && moveLen <= document.body.clientWidth * 0.4) {
            line.style.left = moveLen + 'px'
            left.style.width = moveLen + 'px'
            right.style.width = document.body.clientWidth - moveLen + 'px'
          }
        }
        document.onmouseup = function () {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(val) {

      if (val.isDirectory == '1') {
        this.listQuery.sourceId = val.id
        this.listQuery.database = val.dbName
        this.listQuery.table = val.name.split('-')[0]
        this.getList()
      }
    },
    handlefun(item) {
      item.map((v, i) => {
        if (v.children && v.children.length) {
          this.handlefun(v.children)
        }
        v.label = v.label.split("?")[0]
      })
      return item
    },
    getTreeList() {
      this.listLoading = true
      fetchsourceList(this.listQuery).then((response) => {
        if (response.data.code === 0) {

          this.treeList = response.data.data
          this.treeList = this.treeList.filter((e) => e.label.indexOf('数据抽取任务总目录') == -1)

          this.treeList = this.treeList[0].children.filter(
            (e) => e.label.indexOf('核心层') == -1 && e.label.indexOf('前置库') == -1 && e.label.indexOf('主题层') == -1 && e.id.indexOf('1724329140115152897') == -1
          )
          this.treeList = this.handlefun(this.treeList)
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].id



            this.currentNodekey = this.treeList[0].children[0].children[0].id
            this.handleNodeClick(this.treeList[0].children[0].children[0])
            // this.treeData.push(
            //   this.treeList[0].id,
            //   this.treeList[0].children[0].id,
            //   this.treeList[0].children[0].children[0].id
            // )
            // this.listQuery.sourceId = this.treeList[0].children[0].id
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          // if(this.treeList.length>0){
          // this.listQuery.directoryId = this.treeList[0].id
          // this.currentNodekey = this.treeList[0].id;
          // console.log("1====="+this.treeList[0].id)
          // console.log("2====="+this.treeList[0].children[0].id)
          // console.log("3====="+this.treeList[0].children[0].children[0].id)
          // this.treeData.push(this.treeList[0].id,this.treeList[0].children[0].id,this.treeList[0].children[0].children[0].id)
          // this.listQuery.sourceId = this.treeList[0].children[0].children[0].id
          // this.getList()
          //   this.$nextTick(() => {
          //     this.$refs.SlotTree.setCurrentKey(this.treeList[0].children[0].children[0].id); //一定要加这个选中了否则样式没有出来
          //   });
          // }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getLabelList() {
      this.listLoading = true
      fetchMetadataLabelGroupList(this.listQuery).then((response) => {
        if (response.data.code === 0) {
          this.labelList = response.data.data
          this.listLoading = false
          // this.$refs.form.setList(this.labelList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },

    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) { },
    getList() {
      if (!this.listQuery.sourceId) {
        this.$message.error('请选择一个数据表')
        return
      }

      this.listLoading = true
      getTotalModel(this.listQuery).then((response) => {
        this.list = response.data
        this.obj = this.list[0]
        this.total = this.list.length
        // this.setSort()
        this.listLoading = false
      })
    },
    handleUpdate(row) {
      // this.$refs.form.setList(this.labelList)
      this.$refs.form.handleUpdate(row.id)
    },
    handleUpdate1(row) {
      this.$confirm('确定解除标签绑定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const data = row
        data.labelId = ''
        updatecolumn(data).then((response) => {
          this.loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(row.id).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deletecolumn(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleExport() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.downloadLoading = true
      exportcolumn(this.ids).then((response) => {
        this.downloadLoading = true
        if (response.data.code === 0) {
          import('@/vendor/Export2Excel').then((excel) => {
            excel.export_byte_to_excel(response.data.data.bytes, response.data.data.title)
            this.downloadLoading = false
          })
        } else {
          this.$message.error(response.data.msg)
        }
      })
    },
    setSort() {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          // TODO：这里完成自己的业务处理
        },
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
// table表头固定
// ::v-deep(.el-table)  {
//   overflow: visible;
// }

// ::v-deep(.el-table__header-wrapper)  {
//   position: sticky;
//   top: 0px;//这个值根据实际情况而定
//   z-index: 10;
// }
.el-select {
  width: 30%;
  display: flex;
  justify-content: flex-end;
  margin-right: 10px;
}

::v-deep(.el-table__empty-block) {
  width: 100% !important;
}

#treeBox {
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}

.left-tree {
  position: relative;
  // width: 500px;
  // height: 100%; // 如果存在box-sizing，此处设置就会用会影响，可以先去掉看看效果
  background: #fff;
  // box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  vertical-align: top;
  display: inline-block;
  box-sizing: border-box;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  padding: 10px 0 0 10px;
  // margin-right: 8px;
}

::v-deep(.el-table--scrollable-y .el-table__body-wrapper::-webkit-scrollbar) {
  width: 0 !important;
}

.resize {
  cursor: col-resize;
  position: absolute;
  top: 45%;
  right: -8px;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: 50%;
  font-size: 32px;
  color: #fff;
  display: flex;
  /* 使用 flex 布局 */
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
}

.right-content {
  display: inline-block;
  width: calc(100% - 510px);
  width: 100%;

  background: #fff;
  -webkit-box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  vertical-align: top;
  overflow: auto;
}

::v-deep(::-webkit-scrollbar) {
  display: block !important;
}

.right {
  width: 100%;
  height: 100%;

  .top {
    width: 100%;
    overflow: auto;
  }

  .buttom {
    width: 100%;
    height: 20%;
    margin-top: 10px;
  }
}
</style>
